package com.example.demo.param.service.impl;


import com.example.demo.account.entity.SecurityUser;
import com.example.demo.common.utils.Constant;
import com.example.demo.common.utils.ReflectUtils;
import com.example.demo.common.utils.SpringSecurityUtils;
import com.example.demo.information.entity.School;
import com.example.demo.information.entity.Student;
import com.example.demo.information.entity.info.StudentInfo;
import com.example.demo.param.entity.Param;
import com.example.demo.param.repository.ParamRepository;
import com.example.demo.param.service.ParamService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional(rollbackFor = Exception.class)
public class ParamServiceImpl  implements ParamService {

    @Autowired
    private ParamRepository paramRepository;

    @Override
    public Map<Long, List<Param>> findSchoolPhotoParamMap(String paramPzsm) {
        Map<Long,List<Param>> map = new HashMap<>();
        List<Param> paramList = paramRepository.findByPzsm(paramPzsm);
        for(Param param :paramList){
            Long xxxxId = param.getXxxxId();
            if(map.containsKey(xxxxId)){
                map.get(xxxxId).add(param);
            }else{
                List<Param> list = new ArrayList<>();
                list.add(param);
                map.put(param.getXxxxId(),list);
            }
        }
        return map;
    }

    @Override
    public List<Param> findByPzsmAndXxxxIdNull(String pzsm) {
        return paramRepository.findByPzsmAndXxxxIdNull(pzsm);
    }

    @Override
    public List<Param> findSchoolPhotoParam(Long xxId,String pzsm) {
        return paramRepository.findByXxxxIdAndPzsm(xxId,pzsm);
    }

    @Override
    public void savePhotoParam(Param param, Long xxId, String spid, String bkColor, String xgr) {
        saveOrUpdateParam(param,xxId,Constant.PARAM_PZSM_PHOTO,spid,bkColor,xgr);
    }

    /**
     * 保存或者更新配置值param
     * @param param
     * @param xxId
     * @param pzsm
     * @param pzz
     * @param pzz2
     * @param xgr
     */
    private void saveOrUpdateParam(Param param, Long xxId,String pzsm, String pzz, String pzz2, String xgr){
        Date date = new Date();
        String xgsj = Constant.formatter.get().format(date);
        if(param!=null){
            param.setXgr(xgr);
            param.setXgsj(xgsj);
        }else{
            param = new Param();
            param.setPzsm(pzsm);
            if(xxId!=null){
                param.setXxxxId(xxId);
            }
            param.setLrr(xgr);
            param.setLrsj(xgsj);
        }
        param.setPzz(pzz);
        param.setPzz2(pzz2);
        paramRepository.save(param);
    }

    /**
     * 学校证件照参数JSON
     * @param schoolList
     * @return
     */
    @Override
    public List<Map<String, Object>> loadSchoolPhotoParamJson(List<School> schoolList) {
        List<Map<String,Object>> list = new ArrayList<>();
        Map<Long, List<Param>> schoolPhotoParamMap = findSchoolPhotoParamMap(Constant.PARAM_PZSM_PHOTO);//Map<xxId,List<PhotoParam>>
        String spidStrDefault = "未设置(采用默认)";
        String bkColorStrDefault = "未设置(采用默认)";
        for(School school:schoolList){
            Map<String,Object> paramTempMap = new HashMap<>();
            paramTempMap.put("xxId",school.getId());
            paramTempMap.put("xxmc",school.getName());
            paramTempMap.put("xxmc_short",school.getShort_name());
            List<Param> paramList = schoolPhotoParamMap.get(school.getId());
            if(paramList!=null&&!paramList.isEmpty()){
                for(Param param:paramList){
                    String spidStr = Constant.photoParamSpidMap.get(param.getPzz());
                    if(StringUtils.isNotBlank(spidStr)){
                        String[] split = spidStr.split("@@");
                        spidStr = split[0]+"("+split[1]+")";
                    }else{
                        spidStr = spidStrDefault;
                    }
                    String bkColorStr = Constant.photoParamBkColorMap.get(param.getPzz2());
                    bkColorStr = StringUtils.isNotBlank(bkColorStr)?bkColorStr:bkColorStrDefault;
                    paramTempMap.put("paramId",param.getId());
                    paramTempMap.put("spid",param.getPzz());
                    paramTempMap.put("bkColor",param.getPzz2());
                    paramTempMap.put("spidStr", spidStr);
                    paramTempMap.put("bkColorStr", bkColorStr);
                }
            }else{
                paramTempMap.put("spid","");
                paramTempMap.put("bkColor","");
                paramTempMap.put("spidStr", spidStrDefault);
                paramTempMap.put("bkColorStr", bkColorStrDefault);
            }
            list.add(paramTempMap);
        }
        return list;
    }

    /**
     * 学校证件照导出名JSON
     * @param schoolList
     * @return
     */
    @Override
    public List<Map<String, Object>> loadSchoolPhotoNameParamJson(List<School> schoolList) {
        List<Map<String,Object>> list = new ArrayList<>();
        Map<Long, List<Param>> schoolPhotoParamMap = findSchoolPhotoParamMap(Constant.PARAM_PZSM_PHOTONAME);//Map<xxId,PhotoParam>
        String nameparamDefault = "未设置(采用默认)";
        String nameparamStrDefault = "未设置(采用默认)";
        nameparamDefault = Constant.defaultPhotoNameParam;
        for(School school:schoolList){
            Map<String,Object> paramTempMap = new HashMap<>();
            paramTempMap.put("xxId",school.getId());
            paramTempMap.put("xxmc",school.getName());
            paramTempMap.put("xxmc_short",school.getShort_name());
            List<Param> paramList = schoolPhotoParamMap.get(school.getId());
            Param param = paramList!=null&&!paramList.isEmpty()?paramList.get(0):null;
            String nameParam = nameparamDefault;
            String nameParamStr = nameparamStrDefault;
            String nameParamPre = nameParamStr;
            if(param!=null&&StringUtils.isNotBlank(param.getPzz())){
                nameParam = param.getPzz();
                //分解一下,构成预览内容
                StudentInfo studentInfo = new StudentInfo(Constant.testStudent);
                Map<String, String> photoNameByNameParam = getPhotoNameByNameParam(nameParam, studentInfo);
                nameParamPre = photoNameByNameParam.get("nameParamPre");
                nameParamStr = photoNameByNameParam.get("nameParamStr");
            }
            paramTempMap.put("nameParam",nameParam);
            paramTempMap.put("nameParamStr", nameParamStr);
            paramTempMap.put("nameParamPre", nameParamPre);
            list.add(paramTempMap);
        }
        return list;
    }

    /**
     * 根据xxIds 批量保存照片参数配置
     * @param xxId 为空的话，表示默认的；不为空，以，分割学校
     * @param spid
     * @param bkColor
     * @return
     */
    @Override
    public String savePhotoParamForXxIds(String xxId, String spid, String bkColor) {
        return saveParamForXxIds(xxId,Constant.PARAM_PZSM_PHOTO,spid,bkColor);
    }

    @Override
    public String savePhotoParamForParamIds(String paramId, String spid, String bkColor) {
        return saveParamForParamIds(paramId,Constant.PARAM_PZSM_PHOTO,spid,bkColor);
    }

    /**
     * 根据xxIds 批量保存照片导出名
     * @param xxId 为空的话，表示默认的；不为空，以，分割学校
     * @param photoName
     * @return
     */
    @Override
    public String savePhotoNameParamForXxIds(String xxId, String photoName) {
        return saveParamForXxIds(xxId,Constant.PARAM_PZSM_PHOTONAME,photoName,null);
    }

    /**
     * 根据school学校设置的内容，return 文件名设置
     * @param studentInfo
     * @return
     */
    @Override
    public String getPhotoFileNameByStudentInfo(StudentInfo studentInfo) {
        String pzz = Constant.defaultPhotoNameParam;
        List<Param> paramList = getPhotoParam(Constant.PARAM_PZSM_PHOTONAME,studentInfo.getXxxxId());
        Param param = paramList!=null&&!paramList.isEmpty()?paramList.get(0):null;
        pzz = param!=null&&StringUtils.isNotBlank(param.getPzz())?param.getPzz():pzz;
        Map<String, String> paramMap = getPhotoNameByNameParam(pzz, studentInfo);
        return paramMap.get("nameParamPre");
    }

    /**
     * 根据获得的文件名的配置值导出，return 文件名设置
     * @param studentInfo
     * @param photoNamePzz 根据获得的文件名的配置值导出
     * @return
     */
    @Override
    public String getPhotoFileNameByStudentInfoAndPzz(StudentInfo studentInfo,String photoNamePzz) {
        photoNamePzz = StringUtils.isBlank(photoNamePzz)?Constant.defaultPhotoNameParam:photoNamePzz;
        Map<String, String> paramMap = getPhotoNameByNameParam(photoNamePzz, studentInfo);
        return paramMap.get("nameParamPre");
    }

    /**
     * 批量保存param
     * @param xxId 为空的话，表示默认的；不为空，以,分割学校
     * @param pzsm
     * @param pzz
     * @param pzz2
     * @return
     */
    private String saveParamForXxIds(String xxId,String pzsm, String pzz, String pzz2) {
        SecurityUser currentUserDetails = SpringSecurityUtils.getCurrentUserDetails();
        Long xxIdL;
        if(StringUtils.isNotBlank(xxId)&&xxId.lastIndexOf(",")!=-1){
            String[] split = xxId.split(",");
            int count = 0;
            for(String s:split){
                xxIdL = StringUtils.isBlank(s)?null:Long.valueOf(s);
                if(xxIdL!=null){
                    try{
                        savePhotoParam(xxIdL,pzsm,pzz,pzz2,currentUserDetails.getName());
                        count++;
                    } catch (Exception e) {
                        e.printStackTrace();
                        continue;
                    }
                }
            }
            return "success@@成功操作"+count+"条数据.";
        }else{
            xxIdL = StringUtils.isBlank(xxId)?null:Long.valueOf(xxId);
            savePhotoParam(xxIdL,pzsm,pzz,pzz2,currentUserDetails.getName());
            return "success";
        }
    }

    /**
     * 批量保存param
     * @param paramId 为空的话，表示默认的；不为空，以,分割paramId
     * @param pzsm
     * @param pzz
     * @param pzz2
     * @return
     */
    private String saveParamForParamIds(String paramId,String pzsm, String pzz, String pzz2) {
        SecurityUser currentUserDetails = SpringSecurityUtils.getCurrentUserDetails();
        Long paramIdL;
        if(StringUtils.isNotBlank(paramId)&&paramId.lastIndexOf(",")!=-1){
            String[] split = paramId.split(",");
            int count = 0;
            for(String s:split){
                paramIdL = StringUtils.isBlank(s)?null:Long.valueOf(s);
                if(paramIdL!=null){
                    try{
                        savePhotoParamByParamId(paramIdL,pzsm,pzz,pzz2,currentUserDetails.getName());
                        count++;
                    } catch (Exception e) {
                        e.printStackTrace();
                        continue;
                    }
                }
            }
            return "success@@成功操作"+count+"条数据.";
        }else{
            paramIdL = StringUtils.isBlank(paramId)?null:Long.valueOf(paramId);
            savePhotoParamByParamId(paramIdL,pzsm,pzz,pzz2,currentUserDetails.getName());
            return "success";
        }
    }

    /**
     * 保存param
     * @param xxId 如果xxId为空则找到对应学校的param
     * @param pzsm 设置说明
     * @param pzz  配置1
     * @param pzz2 配置2
     * @param xgr
     */
    private void savePhotoParam(Long xxId,String pzsm,String pzz,String pzz2,String xgr){
        List<Param> paramList = findSchoolPhotoParam(xxId,pzsm);
        Param param = null;
        if(paramList!=null&&paramList.size()>1){//有多条记录需要调整成默认的，就删掉，重新新建一个
            paramRepository.deleteAll(paramList);
        }else{
            param = paramList!=null&&!paramList.isEmpty()?paramList.get(0):null;
        }
        saveOrUpdateParam(param,xxId,pzsm,pzz,pzz2,xgr);
    }

    /**
     * 保存param  2
     * @param paramId 前提对象存在才能保存
     * @param pzsm 设置说明
     * @param pzz  配置1
     * @param pzz2 配置2
     */
    private void savePhotoParamByParamId(Long paramId, String pzsm, String pzz, String pzz2, String xgr) {
        Param param = paramRepository.findById(paramId).get();
        if(param!=null){
            saveOrUpdateParam(param,param.getXxxxId(),pzsm,pzz,pzz2,xgr);
        }
    }


    /**
     * 获取当前的配置值  学校没有  查超级管理员设置  ；超级管理员没有设置   用系统默认；
     * @param pzsm
     * @param xxId
     * @return
     */
    @Override
    public List<Param> getPhotoParam(String pzsm,Long xxId){
        List<Param> paramList = new ArrayList<>();
        if(xxId!=null){
            paramList = findSchoolPhotoParam(xxId,pzsm);
        }
        if(paramList==null||paramList.isEmpty()){
            paramList = findByPzsmAndXxxxIdNull(pzsm);
        }
        return paramList;
    }

    /**
     * 根据设置的导出名参数,导出当前学生的导出名
     * @param nameParam   name_sfz
     * @param studentInfo  name:小明  sfz:123456
     * @return  nameParamStr(返回形式)   nameParamPre(根据studentInfo拼接的返回值)
     */
    @Override
    public Map<String,String> getPhotoNameByNameParam(String nameParam,StudentInfo studentInfo){
        Map<String,String > returnMap = new HashMap<>();
        nameParam = StringUtils.isNotBlank(nameParam)?nameParam:Constant.defaultPhotoNameParam;
        String nameParamStr = nameParam;//学生姓名_身份证
        String nameParamPre = nameParam;//小明_123456
        Map<String, String> photoNameParamFromStuMap = Constant.photoNameParamFromStuMap;
        Set<String> photoNameParamFromStuList = photoNameParamFromStuMap.keySet();
        for(String param:photoNameParamFromStuList){
            String paramP = "@"+param+"@";
            if(nameParam.lastIndexOf(paramP)!=-1){
                String paramStr = photoNameParamFromStuMap.get(param);
                String paramPre = paramStr;
                try {
                    paramPre = (String) ReflectUtils.getGetMethod(studentInfo, param);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                paramPre = paramPre==null?paramStr:paramPre;
                nameParam = nameParam.replace(paramP,"");
                nameParamStr = nameParamStr.replace(paramP,paramStr);
                nameParamPre = nameParamPre.replace(paramP,paramPre);
            }
        }
        Map<String, String> photoNameParamFromStuMapOther = Constant.photoNameParamFromStuMapOther;
        Set<String> photoNameParamFromStuOtherList = photoNameParamFromStuMapOther.keySet();
        for(String param:photoNameParamFromStuOtherList){
            String paramP = "@"+param+"@";
            if(nameParam.lastIndexOf(paramP)!=-1){
                String paramStr = photoNameParamFromStuMapOther.get(param);
                String paramPre = paramStr;
                try {
                    paramPre = (String) ReflectUtils.getGetMethod(studentInfo, param.replace('_','.'));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                switch (param){
                    case "school_name":
                    paramPre = studentInfo.getXxmc();
                    break;
                    case "bjxx_name":
                    paramPre = studentInfo.getBjmc();
                    break;
                    default:
                        paramPre = paramStr;
                }
                paramPre = paramPre==null?paramStr:paramPre;
                nameParam = nameParam.replace(paramP,"");
                nameParamStr = nameParamStr.replace(paramP,paramStr);
                nameParamPre = nameParamPre.replace(paramP,paramPre);
            }
        }
        Map<String, ThreadLocal<SimpleDateFormat>> photoNameParamFromDateMap = Constant.photoNameParamFromDateMap;
        Map<String, String> photoNameParamFromDateToStrMap = Constant.photoNameParamFromDateToStrMap;
        Set<String> photoNameParamFromDateList = photoNameParamFromDateMap.keySet();
        for(String param:photoNameParamFromDateList){
            String paramP = "@"+param+"@";
            if(nameParam.lastIndexOf(paramP)!=-1){
                String datePre = photoNameParamFromDateMap.get(param).get().format(new Date());
                String dateStr = photoNameParamFromDateToStrMap.get(param);
                nameParam = nameParam.replace(paramP,"");
                nameParamStr = nameParamStr.replace(paramP,dateStr);
                nameParamPre = nameParamPre.replace(paramP,datePre);
            }
        }
        returnMap.put("nameParamStr",nameParamStr);
        returnMap.put("nameParamPre",nameParamPre);
        return returnMap;
    }
}
